package com.http.nio.core;

import java.io.IOException;

/**
 * @author YL
 */
public class CloudService {

    private final CloudServlet[] cloudServlets;

    public CloudService(CloudServlet[] cloudServlets) {
        this.cloudServlets = cloudServlets;
    }

    public void doService(Request request, Response response) {
        if (cloudServlets.length == 0) {
            response.setCode(500);
            try {
                response.getOutPutStream().write("No Servlet".getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }

        CloudServlet servlet = doSelect(request);
        try {
            servlet.init(request, response);
            servlet.doService(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            response.setCode(502);
        }
    }

    private CloudServlet doSelect(Request request) {
        for (CloudServlet cloudServlet : cloudServlets) {
            if (cloudServlet.match(request)) {
                return cloudServlet;
            }
        }
        // 没有命中 使用默认解析器
        return cloudServlets[0];
    }

}
